<!-- components/CustomNavbar.vue -->
<template>
	<view class="custom-navbar"
		:style="{
			background: bgColor,
			position: fixed ? 'fixed' : 'relative',
			top: fixed ? '0' : 'auto',
			zIndex: 999
		}"
	>
		<!-- 占位状态栏 -->
		<view :style="{ height: statusBarHeight * 2 + 'rpx' }"></view>

		<!-- 导航栏内容 -->
		<view class="nav-content" :style="{ height: navHeight + 'rpx' }">
			<!-- 返回按钮 -->
			<view v-if="showBack" class="back-btn" @tap="onBack">
				<uv-icon name="arrow-left" :size="iconSize" :color="iconColor" />
			</view>

			<!-- 标题 -->
			<view class="title" :style="{ fontSize: titleSize, color: titleColor }">
				{{ title }}
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue'

	const props = defineProps({
		title: {
			type: String,
			default: '标题'
		},
		showBack: {
			type: Boolean,
			default: true
		},
		iconColor: {
			type: String,
			default: '#000'
		},
		iconSize: {
			type: [String, Number],
			default: 20
		},
		titleColor: {
			type: String,
			default: '#000'
		},
		titleSize: {
			type: String,
			default: '32rpx'
		},
		backgroundColor: {
			type: String,
			default: 'transparent'
		},
		fixed: {
			type: Boolean,
			default: false
		},
		scroll: {
			type: Boolean,
			default: false
		}
	})

	const emit = defineEmits(['back', 'height-ready'])

	const statusBarHeight = ref(0)
	const navHeight = ref(44)

	const opacity = ref(0)
	const bgColor = computed(() => {
		if (props.scroll) {
			// 背景色变成带透明度的 rgba 色值
			// 这里只以白色为例，你可以根据 props.backgroundColor 做转换
			return `rgba(255, 255, 255, ${opacity.value})`
		}
		return props.backgroundColor
	})

	onMounted(() => {
		const sys = uni.getSystemInfoSync()
		statusBarHeight.value = sys.statusBarHeight || 20

		// 小程序中更精确计算导航栏高度
		// 注意：getMenuButtonBoundingClientRect 仅在小程序可用
		// App 中 fallback 使用默认值

		// #ifdef MP-WEIXIN
		const menuButton = uni.getMenuButtonBoundingClientRect()
		console.log(menuButton, 'menuButton');
		if (menuButton && sys.statusBarHeight) {
			navHeight.value = menuButton.bottom + menuButton.top - sys.statusBarHeight
		}
		// #endif

		const totalHeight = statusBarHeight.value * 2 + navHeight.value
		emit('height-ready', totalHeight)
	})

	const handleScroll = (e) => {
		const top = e.scrollTop || 0
		const maxScroll = 100
		opacity.value = Math.min(1, top / maxScroll)
	}
	
	defineExpose({
	  handleScroll
	})

	// 点击返回按钮
	const onBack = () => {
		emit('back')
	}
</script>

<style lang="scss" scoped>
	.custom-navbar {
		width: 100%;

		.nav-content {
			display: flex;
			align-items: center;
			justify-content: center;
			position: relative;

			.back-btn {
				position: absolute;
				left: 30rpx;
				display: flex;
				align-items: center;
				width: 120rpx;
				height: 100%;
			}

			.title {
				flex: 1;
				height: 100%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: bold;
			}
		}
	}
</style>